package com.example.demo.socket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.entity.UsersInfo;
import com.example.demo.service.IUsersInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/*
 * @Author:大力王
 * @Date:2024/3/31-31-17:31
 * 开始了
 */
@Component
@ServerEndpoint("/gift/{userId}")
public class GiftSocketServer {
    private final Logger logger = LoggerFactory.getLogger(GiftSocketServer.class);
    private static final Map<String, Session> CLIENTS = new ConcurrentHashMap<>();
    private static final Map<String, AtomicInteger> TERMINAL_IDS = new HashMap<>();
    private static final Map<String, SocketGiftInfo> map = new HashMap<>();

    @Resource
    private IUsersInfoService iUsersInfoService;
    /**
     * 连接建立成功时触发
     * @param session 当前会话
     */
    @OnOpen
    public void onOpen( Session session) {
        logger.info(session.getRequestURI().getPath() + "，打开连接开始：" + session.getId());

    }
    /**
     * 收到客户端消息时触发
     * @param message 客户端发送过来的消息
     * @param session 当前会话
     */
    @OnMessage
    public void onMessage( String message, @PathParam("userId")String userId, Session session) {
        logger.info(session.getRequestURI().getPath() + "，收到消息：" + message);
        JSONObject jsonObject = JSONUtil.parseObj(message);
        String msg = jsonObject.getStr("msg");
        String ids = jsonObject.getStr("id");
        //通过id获取到map对象里面的session
//        Session sessions = map.get(ids).getSession();
        logger.info(ids);
        //谁说了什么
        UsersInfo usersInfo =  iUsersInfoService.getById(ids);
        logger.info(usersInfo.getNickname());
        JSONObject json1 = JSONUtil.createObj()
                .put("nickName", usersInfo.getNickname())
                .put("msg", msg);
        //礼物推送
        try {
            //通过session长连接隧道给前端推送信息
            session.getBasicRemote().sendText(json1.toString());
        } catch (IOException e) {
            logger.info(session.getRequestURI().getPath() + "，发生错误：" + e.getMessage());
        }
    }
    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose( Session session) {
        logger.info(session.getRequestURI().getPath() + "，关闭连接：" + session.getId());
    }
    /**
     * 发生错误时触发
     * @param session 当前会话
     * @param error 错误信息
     */
    @OnError
    public void onError( Session session, Throwable error) {
        logger.error(session.getRequestURI().getPath() + "，发生错误：" + error.getMessage());
    }
}
